/*
 *    Copyright 2009-2021 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.parsing;

/**
 * @author Clinton Begin
 */
public class GenericTokenParser {

  private final String openToken;
  private final String closeToken;
  private final TokenHandler handler;

  public GenericTokenParser(String openToken, String closeToken, TokenHandler handler) {
    this.openToken = openToken;
    this.closeToken = closeToken;
    this.handler = handler;
  }

  public String parse(String text) {
    if (text == null || text.isEmpty()) {
      return "";
    }
    // 记录开始占位符的起始索引
    // search open token
    int start = text.indexOf(openToken);
    if (start == -1) {
      return text;
    }
    char[] src = text.toCharArray();
    // 偏移量(当前位置索引)
    int offset = 0;
    final StringBuilder builder = new StringBuilder();
    StringBuilder expression = null;
    do {
      // 有占位符的情况, 开始占位符前一个字符为转义字符
      // 这里处理是跳过被转义了的占位符, 将其当做普通字符串处理
      if (start > 0 && src[start - 1] == '\\') {
        // this open token is escaped. remove the backslash and continue.
        builder.append(src, offset, start - offset - 1).append(openToken);

        // 更新偏移量
        offset = start + openToken.length();
      } else {

        // 没有占位符的情况

        // found open token. let's search close token.
        if (expression == null) {
          // 首次执行的初始化动作
          expression = new StringBuilder();
        } else {

          // 重置(清空上一次记录的值)
          expression.setLength(0);
        }

        // 记录下一个开始占位符到当前索引位置的字符串
        // 当前索引位置 offset 肯定是小于等于下一个开始占位符的起始索引的
        // 如果是首次执行, 那么两个值都是 0, 记录的字符串为""
        builder.append(src, offset, start - offset);

        // 移动当前索引到下一个开始占位符的末尾索引
        offset = start + openToken.length();

        // 找下一个结束占位符的起始索引
        int end = text.indexOf(closeToken, offset);

        while (end > -1) {

          // 配到了结束占位符

          // 有占位符的情况, 结束占位符前一个字符为转义字符
          // 这里处理是跳过被转义了的占位符, 将其当做普通字符串处理
          if (end > offset && src[end - 1] == '\\') {
            // this close token is escaped. remove the backslash and continue.
            expression.append(src, offset, end - offset - 1).append(closeToken);

            // 更新偏移量
            offset = end + closeToken.length();

            // 找下一个结束占位符的起始索引
            end = text.indexOf(closeToken, offset);
          } else {

            // 没得占位符的情况

            // 这里是拿到表达式, 也就是下一个开始占位符到结束占位符包含的内容
            // 比如占位符是:${ }, 那么 ${name} 取到的内容就是 name
            expression.append(src, offset, end - offset);
            break;
          }
        }

        // 结束占位符没找到
        if (end == -1) {

          // close token was not found.

          // 拼接剩下的字符串
          // 从下个开始占位符的起始位置算起, 到末尾
          builder.append(src, start, src.length - start);

          // 将当前位置索引置位末尾, 用于跳出循环
          offset = src.length;
        } else {

          // 根据表达式获取真实值
          builder.append(handler.handleToken(expression.toString()));

          // 更新当前位置索引
          // 偏移结束占位符的长度
          offset = end + closeToken.length();
        }
      }

      // 记录开始占位符的起始索引
      // 匹配下一个开始占位符的起始索引
      start = text.indexOf(openToken, offset);
    } while (start > -1);

    // 拼接剩下的字符串
    // 如果当前位置索引不在末尾
    if (offset < src.length) {
      builder.append(src, offset, src.length - offset);
    }
    return builder.toString();
  }
}
